<?php

abstract class Kd_Web_Router {

    private $_baseUrl = '/';
	private $_urlInfo = NULL;
	
    public function __construct() {
		$this->initialize();
    }
    
	protected function initialize(){}

    public function getArguments() {
        return $this->urlInfo['query'];
    }

    public function getPathUrl() {
        $result = $this->urlInfo['path'];
        return substr($result, strlen($this->getBaseUrl()));
    }

    public function route($url = NULL){
    	if(is_null($url)){
    		$url = $_SERVER["REQUEST_URI"];
    	}
    	$this->_urlInfo = $this->parseUrl($url);
    	return $this;
    }

    public function getBaseUrl() {
        return $this->_baseUrl;
    }

    public function setBaseUrl($value) {
    	if(empty($this->_baseUrl)){
    		return '/';
    	}
        $this->_baseUrl = $value;
    }

    protected function buildUrlArguments(array $arguments) {
        $result = array();
        foreach ($arguments as $key => $val) {
            if (is_array($val)) {
                $result[$key] = $this->buildUrlArguments($val);
            } else {
                if (!is_null($val) && strlen((string) $val) > 0) {
                    $result[$key] = $val;
                }
            }
        }
        return $result;
    }

    public function buildUrl($fragment, $arguments = array()) {
        $result = $this->getBaseUrl() . $fragment;
        if (!empty($arguments)) {
            $args = http_build_query($arguments);
            return $result . '?' . $args;
        }
        return $result;
    }

    public function parseUrl($url) {
        $result = parse_url($url);
        $result['query'] = isset($this->urlInfo['query']) ?
                				 parse_str($this->urlInfo['query']) :
                				 array();
        return $result;
    }
}